#include "../include/FCFS.h"

// 时间戳
int timestamp = 0;

int fifc_run(char *process) {
    // 设置两个进程循环
    pthread_t th;
    pthread_create(&th, NULL, time_add, (void *) &timestamp);
    PCB *head = (PCB *) malloc(sizeof(PCB));
    head->next = NULL;
    for (int j = 0; j < 4; ++j) {
        PCB *pcb = createThread();
        sleep(1);
        insert_sort_PCB(head, pcb);
    }
    run_fcfs(head);
    return 0;
}

void *time_add(void *time) {
    while (1) {
        timestamp++;
    }
}

PCB *createThread() {
    int temp = timestamp;
    char name[30] = "thread_t";
    sprintf(name, "thread_%d", temp);
    PCB *pcbnode = (PCB *) malloc(sizeof(PCB));
    strcpy(pcbnode->name, name);
    pcbnode->comet = temp;
    pcbnode->state = 0;
    pcbnode->next = NULL;
    return pcbnode;
}

void insert_sort_PCB(PCB *head, PCB *node) {
    PCB *temp = head;
    if (temp->next) {
        while (temp->next) {
            if (temp->next->comet > node->comet) {
                node->next = temp->next;
                temp->next = node;
                return;
            }
            temp = temp->next;
        }
    }
    temp->next = node;
}

void run_fcfs(PCB *head) {
    int temp = timestamp;
    while (1) {
        if (!head->next) {
            return;
        }
        printf("进程 %s 正在运行\n", head->next->name);
        sleep(1);
        if (timestamp - temp >= head->next->comet) {
            head->next = head->next->next;
        }
    }
}